import ScorePanel from "./ScorePanel";
import Snake from "./Snake";
import Food from "./food";

class GameControl {
  snake: Snake;
  food: Food;
  scorePanel: ScorePanel;
  direction: string = ''
  isLive = true
  constructor() {
    this.snake = new Snake()
    this.food = new Food()
    this.scorePanel = new ScorePanel(10,2)

    this.init()
  }

  init() {
    document.addEventListener('keydown', this.keydownHandler.bind(this))
    this.run()
  }
  //   ArrowDown
  //  ArrowRight
  //  ArrowLeft
  //  ArrowUp
  keydownHandler(event: KeyboardEvent) {
    // console.log(event.key);
    this.direction = event.key

  }

  run() {
    let x = this.snake.x
    let y = this.snake.y
    switch (this.direction) {
      case 'ArrowUp':
      case 'Up':
        y -= 10
        break;
      case 'ArrowDown':
      case 'Down':
        y += 10
        break;
      case 'ArrowLeft':
      case 'Left':
        x -= 10
        break;
      case 'ArrowRight':
      case 'Right':
        x += 10
        break;
    }
    this.checkEat(x, y)
    try {
      this.snake.x = x
      this.snake.y = y
    } catch (e) {
      alert(e)
      // console.log(e);
      this.isLive = false
    }
    this.isLive && setTimeout(this.run.bind(this), 300 - (this.scorePanel.level - 1) * 30)
  }
  checkEat(x: number, y: number) {
    if (x === this.food.x && y === this.food.y) {
      this.food.change()
      this.scorePanel.addScore()
      this.snake.addBobe()
    }
  }
}
export default GameControl